package com.web.exiaodao.business.service.impl;

import com.google.common.collect.Lists;
import com.web.exiaodao.business.constant.JConstant;
import com.web.exiaodao.business.entity.Order;
import com.web.exiaodao.business.entity.OrderDetail;
import com.web.exiaodao.business.repository.OrderDetailRepository;
import com.web.exiaodao.business.repository.OrderRepository;
import com.web.exiaodao.business.service.OrderService;
import com.web.webstart.base.constant.XaConstant;
import com.web.webstart.base.excelUtil.ExcelColumn;
import com.web.webstart.base.excelUtil.ExcelHead;
import com.web.webstart.base.excelUtil.ExcelHelper;
import com.web.webstart.base.exception.BusinessException;
import com.web.webstart.base.service.impl.BaseService;
import com.web.webstart.base.util.DateUtils;
import com.web.webstart.base.util.ReflectionUtils;
import com.web.webstart.base.util.XaUtil;
import com.web.webstart.base.util.jpa.DynamicSpecifications;
import com.web.webstart.base.util.jpa.SearchFilter;
import com.web.webstart.base.util.jpa.SearchFilter.Operator;
import com.web.webstart.base.util.jpa.WebUitl;
import com.web.webstart.base.util.result.XaResult;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.log4j.Logger;
import org.apache.poi.ss.usermodel.Cell;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

@Service("OrderService")
@Transactional(readOnly = false)
public class OrderServiceImpl extends BaseService<Order> implements OrderService {

    private static final Logger LOGGER = Logger.getLogger(OrderServiceImpl.class);

    @Autowired
    private OrderRepository orderRepository;
    @Autowired
    OrderDetailRepository orderDetailRepository;

    /**
     * 查询单条Order信息
     * //@param tId
     *
     * @return 返回单个Order对象
     * @throws BusinessException
     */
    @Transactional(readOnly = true, rollbackFor = Exception.class)
    public XaResult<Order> findOne(Long modelId) throws BusinessException {
        Order obj = new Order();
        if (modelId != 0) {
            obj = orderRepository.findByIdAndStatusNot(modelId, XaConstant.Status.delete);
        }
        XaResult<Order> xr = new XaResult<Order>();
        if (XaUtil.isNotEmpty(obj)) {
            xr.setObject(obj);
            LOGGER.info("后台----->查询单个实体----->Order");
        } else {
            xr.error(XaConstant.Message.object_not_find);
            LOGGER.info(XaConstant.Message.object_not_find);
        }
        return xr;
    }

    /**
     * 查询单条Order信息
     * //@param tId
     *
     * @return 返回单个Order对象
     * @throws BusinessException
     */
    @Transactional(readOnly = true, rollbackFor = Exception.class)
    public XaResult<List<Map<String, Object>>> findOneDetial(Long modelId) throws BusinessException {
        Order obj = new Order();
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        if (modelId != 0) {
        	Map<String, Object> map = new HashMap<String, Object>();
        	
            obj = orderRepository.findByIdAndStatusNot(modelId, XaConstant.Status.delete);
            
            String addressId = obj.getAddressId();
            int count = 0;
//			if(StringUtils.isNotEmpty(addressId)){
//				map = processMap(map,list,++count,"收货地址id:",addressId);
//			}

            String billContent = obj.getBillContent();
            if (StringUtils.isNotEmpty(billContent)) {
                map = processMap(map, list, ++count, "发票内容:", billContent);
            }

            int billEtype = obj.getBillEtype() == null ? 0 : obj.getBillEtype();
            if (billEtype > 0) {
                String billEtypeStr = billEtype == 1 ? "纸质发票" : "电子发票";
                map = processMap(map, list, ++count, "发票类型:", billEtypeStr);
            }

            String billTitle = obj.getBillTitle();
            if (StringUtils.isNotEmpty(billTitle)) {
                map = processMap(map, list, ++count, "发票抬头:", billTitle);
            }

            int billType = obj.getBillType() == null ? 0 : obj.getBillType();
            if (billType > 0) {
                String billTypeStr = billType == 1 ? "个人" : "公司";
                map = processMap(map, list, ++count, "发票类型:", billTypeStr);
            }

            String nullString = null;
            if(count == 0){
            	String consigneeAdress = obj.getConsigneeAdress();
            	if (StringUtils.isNotEmpty(consigneeAdress)) {
            		map = processMap(map, list, ++count, "收货人地址:", consigneeAdress);
            	}
            	count = count + 1;
            	map = processMap(map, list, count, "", nullString);
            }else if(count > 0 && count % 2 == 0){
            	String consigneeAdress = obj.getConsigneeAdress();
            	if (StringUtils.isNotEmpty(consigneeAdress)) {
            		map = processMap(map, list, ++count, "收货人地址:", consigneeAdress);
            	}
            	count = count + 1;
            	map = processMap(map, list, count, "", nullString);
            }else{
            	count = count + 1;
            	map = processMap(map, list, count, "", nullString);
            	String consigneeAdress = obj.getConsigneeAdress();
            	if (StringUtils.isNotEmpty(consigneeAdress)) {
            		map = processMap(map, list, ++count, "收货人地址:", consigneeAdress);
            	}
            	count = count + 1;
            	map = processMap(map, list, count, "", nullString);
            }
            String consigneeName = obj.getConsigneeName();
            if (StringUtils.isNotEmpty(consigneeName)) {
                map = processMap(map, list, ++count, "收货人姓名:", consigneeName);
            }
            String consigneeTel = obj.getConsigneeTel();
            if (StringUtils.isNotEmpty(consigneeTel)) {
                map = processMap(map, list, ++count, "收货人电话:", consigneeTel);
            }
            int deducted_money = obj.getDeducted_money() == null ? 0 : obj.getDeducted_money();
            if (deducted_money > 0) {
                map = processMap(map, list, ++count, "抵扣金额:", deducted_money);
            }
            String expressCompany = obj.getExpressCompany();
            if (StringUtils.isNotEmpty(expressCompany)) {
                map = processMap(map, list, ++count, "物流公司:", expressCompany);
            }
            String expressNumber = obj.getExpressNumber();
            if (StringUtils.isNotEmpty(expressNumber)) {
                map = processMap(map, list, ++count, "物流运单号:", expressNumber);
            }
            double goodsTotalPrices = obj.getGoodsTotalPrices() == null ? 0 : obj.getGoodsTotalPrices();
            if (goodsTotalPrices > 0) {
                map = processMap(map, list, ++count, "商品总价:", goodsTotalPrices);
            }
            int hourse_checkin_duration = obj.getHourse_checkin_duration() == null ? 0 : obj.getHourse_checkin_duration();
            if (hourse_checkin_duration > 0) {
                map = processMap(map, list, ++count, "入住时长:", hourse_checkin_duration);
            }
            String hourse_checkin_duration_unit = obj.getHourse_checkin_duration_unit();
            if (StringUtils.isNotEmpty(hourse_checkin_duration_unit)) {
                map = processMap(map, list, ++count, "入住时长单位:", hourse_checkin_duration_unit);
            }
            String hourse_checkinTime = obj.getHourse_checkinTime();
            if (StringUtils.isNotEmpty(hourse_checkinTime)) {
                map = processMap(map, list, ++count, "酒店房间预约入住时间:", hourse_checkinTime);
            }
            String insVisitCompany = obj.getInsVisitCompany();
            if (StringUtils.isNotEmpty(insVisitCompany)) {
                map = processMap(map, list, ++count, "机构-参观公司:", insVisitCompany);
            }
            String insVisitPurpose = obj.getInsVisitPurpose();
            if (StringUtils.isNotEmpty(insVisitPurpose)) {
                map = processMap(map, list, ++count, "机构-参观目的:", insVisitPurpose);
            }
            String leaveMsg = obj.getLeaveMsg();
            if (StringUtils.isNotEmpty(leaveMsg)) {
                map = processMap(map, list, ++count, "给卖家留言:", leaveMsg);
            }
            String order_Cancle_DateTime = obj.getOrderReceivingDatetime();
            if (StringUtils.isNotEmpty(order_Cancle_DateTime)) {
                map = processMap(map, list, ++count, "订单取消时间:", order_Cancle_DateTime);
            }
            String order_Dead_DateTime = obj.getOrder_Dead_DateTime();
            if (StringUtils.isNotEmpty(order_Dead_DateTime)) {
                map = processMap(map, list, ++count, "订单失效时间:", order_Dead_DateTime);
            }
            String order_DeliverGoods_DateTime = obj.getOrder_DeliverGoods_DateTime();
            if (StringUtils.isNotEmpty(order_DeliverGoods_DateTime)) {
                map = processMap(map, list, ++count, "订单发货时间:", order_DeliverGoods_DateTime);
            }
            String order_PAY_DateTime = obj.getOrder_PAY_DateTime();
            if (StringUtils.isNotEmpty(order_PAY_DateTime)) {
                map = processMap(map, list, ++count, "订单付款时间:", order_PAY_DateTime);
            }
            String order_Sucess_DateTime = obj.getOrder_Sucess_DateTime();
            if (StringUtils.isNotEmpty(order_Sucess_DateTime)) {
                map = processMap(map, list, ++count, "订单成交时间:", order_Sucess_DateTime);
            }
            String orderNo = obj.getOrderNo();
            if (StringUtils.isNotEmpty(orderNo)) {
                map = processMap(map, list, ++count, "主订单编号:", orderNo);
            }
            String orderState = obj.getOrderState();
            if (StringUtils.isNotEmpty(orderState)) {
                String orderStateStr = "";
                switch (orderState) {
                    case "0":
                        orderStateStr = "待支付";
                        break;
                    case "1":
                        orderStateStr = "已支付";
                        break;
                    case "2":
                        orderStateStr = "待收货";
                        break;
                    case "3":
                        orderStateStr = "待评价";
                        break;
                    case "4":
                        orderStateStr = "交易完成";
                        break;
                    case "5":
                        orderStateStr = "交易关闭";
                        break;
                    default:
                        break;
                }
                map = processMap(map, list, ++count, "订单状态:", orderStateStr);
            }
            double orderTotalPirce = obj.getOrderTotalPirce() == null ? 0 : obj.getOrderTotalPirce();
            if (orderTotalPirce > 0) {
                map = processMap(map, list, ++count, "订单总价:", orderTotalPirce);
            }
            String orderType = obj.getOrderType();
            if (StringUtils.isNotEmpty(orderType)) {
                String orderTypeStr = "";
                switch (orderType) {
                    case "1":
                        orderTypeStr = "普通商品";
                        break;
                    case "2":
                        orderTypeStr = "兑换商品";
                        break;
                    case "3":
                        orderTypeStr = "玩 /艺术品";
                        break;
                    case "51":
                        orderTypeStr = "住";
                        break;
                    case "52":
                        orderTypeStr = "机构参观";
                        break;
                    case "53":
                        orderTypeStr = "旅游/游学";
                        break;
                    case "62":
                        orderTypeStr = "家政护理";
                        break;
                    case "63":
                        orderTypeStr = "医疗服务|医疗康复";
                        break;
                    case "64":
                        orderTypeStr = "护理培训|培训义工";
                        break;
                    default:
                        break;
                }
                map = processMap(map, list, ++count, "订单类型:", orderTypeStr);
            }
            String orderVilidaty = obj.getOrderVilidaty();
            if (StringUtils.isNotEmpty(orderVilidaty)) {
                map = processMap(map, list, ++count, "订单有效期:", orderVilidaty);
            }
            int payment_Kind = obj.getPaymentKind() == null ? 0 : obj.getPaymentKind();
            if (payment_Kind > 0) {
                String payment_KindStr = "";
                switch (payment_Kind) {
                    case 0:
                        payment_KindStr = "微信";
                        break;
                    case 1:
                        payment_KindStr = "支付宝";
                        break;
                    case 2:
                        payment_KindStr = "银联";
                        break;
                    case 3:
                        payment_KindStr = "钱包";
                        break;

                    default:
                        break;
                }
                map = processMap(map, list, ++count, "支付种类:", payment_KindStr);
            }
            double postage = obj.getPostage() == null ? 0 : obj.getPostage();
            if (postage > 0) {
                map = processMap(map, list, ++count, "邮费:", postage);
            }
            String service_appointment_time = obj.getService_appointment_time();
            if (StringUtils.isNotEmpty(service_appointment_time)) {
                map = processMap(map, list, ++count, "服务-预约服务时间:", service_appointment_time);
            }
            String service_idCard = obj.getService_idCard();
            if (StringUtils.isNotEmpty(service_idCard)) {
                map = processMap(map, list, ++count, "服务-身份证号:", service_idCard);
            }
            long service_num = obj.getService_num() == null ? 0 : obj.getService_num();
            if (service_num > 0) {
                map = processMap(map, list, ++count, "服务-商品数量:", service_num);
            }
//			long service_object_id = obj.getService_object_id()==null?0:obj.getService_object_id();
//			if(service_object_id>0){
//				map = processMap(map,list,++count,"服务类专用-对象Id:",service_object_id);
//			}
            String service_phone = obj.getService_phone();
            if (StringUtils.isNotEmpty(service_phone)) {
                map = processMap(map, list, ++count, "服务-手机号:", service_phone);
            }
            double service_price = obj.getService_price() == null ? 0 : obj.getService_price();
            if (service_price > 0) {
                map = processMap(map, list, ++count, "服务-单价:", service_price);
            }
            String service_userName = obj.getService_userName();
            if (StringUtils.isNotEmpty(service_userName)) {
                map = processMap(map, list, ++count, "服务-联系人:", service_userName);
            }
//			String standardIds = obj.getStandardIds();
//			if(StringUtils.isNotEmpty(standardIds)){
//				map = processMap(map,list,++count,"选择的规格Ids:",standardIds);
//			}
//			long userId = obj.getUserId()==null?0:obj.getUserId();
//			if(userId>0){
//				map = processMap(map,list,++count,"购买人ID:",userId);
//			}
          //商品详情
            if(Integer.parseInt(obj.getOrderType().toString())==JConstant.Order_CommentType.GOODS){
            	List<OrderDetail> orderDetailList = orderDetailRepository.findByOrderNoAndStatusNot(obj.getOrderNo(), XaConstant.Status.delete);
            	if(XaUtil.isNotEmpty(orderDetailList)){
//            		map = processMap(map,list,99,"商品详情:",orderDetailList);
            		for (int i = 0; i < orderDetailList.size(); i++) {
            			if(count > 0 && count % 2 == 0){
            				String shopName = orderDetailList.get(i).getShopName();
                			if (StringUtils.isNotEmpty(shopName)) {
                				map = processMap(map, list, ++count, "商品名称:", shopName);
                			}
                			count = count + 1;
            				map = processMap(map, list, count, "", nullString);
            			}else{
            				count = count + 1;
            				map = processMap(map, list, count, "", nullString);
            				String shopName = orderDetailList.get(i).getShopName();
            				if (StringUtils.isNotEmpty(shopName)) {
            					map = processMap(map, list, ++count, "商品名称:", shopName);
            				}
            				count = count + 1;
            				map = processMap(map, list, count, "", nullString);
            			}
            			if(count > 0 && count % 2 == 0){
            				String standardValues = orderDetailList.get(i).getStandardValues();
            				if (StringUtils.isNotEmpty(standardValues)) {
            					map = processMap(map, list, ++count, "商品规格:", standardValues);
            				}
            			}else{
            				count = count + 1;
            				map = processMap(map, list, count, "", nullString);
            				String standardValues = orderDetailList.get(i).getStandardValues();
            				if (StringUtils.isNotEmpty(standardValues)) {
            					map = processMap(map, list, ++count, "商品规格:", standardValues);
            				}
            				count = count + 1;
            				map = processMap(map, list, count, "", nullString);
            			}
            			String shop_ProductSPU = orderDetailList.get(i).getShop_ProductSPU();
            			if (StringUtils.isNotEmpty(shop_ProductSPU)) {
            				map = processMap(map, list, ++count, "商品货号:", shop_ProductSPU);
            			}
            			Long productNum =orderDetailList.get(i).getProductNum()==null?0:orderDetailList.get(i).getProductNum();
            			map = processMap(map, list, ++count, "购买数量:", productNum);
            			double productOrderPrice =orderDetailList.get(i).getProductOrderPrice()==null?0:orderDetailList.get(i).getProductOrderPrice();
            			if(productOrderPrice > 0){
            				map = processMap(map, list, ++count, "商品实销价:", productOrderPrice);
            			}
            			double shopOriginalPrice =orderDetailList.get(i).getShopOriginalPrice()==null?0:orderDetailList.get(i).getShopOriginalPrice();
            			if(shopOriginalPrice > 0){
            				map = processMap(map, list, ++count, "商品原价:", shopOriginalPrice);
            			}
            			Boolean isComm = orderDetailList.get(i).getComm()?true:false;
            			if(orderDetailList.get(i).getComm()){
            				map = processMap(map, list, ++count, "是否评价:", "是");
            			}else{
            				map = processMap(map, list, ++count, "是否评价:", "否");
            			}
					}
            	}
            }
        }
        XaResult<List<Map<String, Object>>> xr = new XaResult<List<Map<String, Object>>>();
        if (XaUtil.isNotEmpty(list)) {
            xr.setObject(list);
            LOGGER.info("后台----->查询单个实体----->Order");
        } else {
            xr.error(XaConstant.Message.object_not_find);
            LOGGER.info(XaConstant.Message.object_not_find);
        }
        return xr;
    }


    /**
     * 分装返回的数据
     *
     * @param map
     * @param list
     * @return
     */
    private Map<String, Object> processMap(Map<String, Object> map,
                                           List<Map<String, Object>> list, int count, String key, Object val) {
        if (count > 0 && count % 2 == 0) {
            map.put("key2", key);
            map.put("val2", val);
            list.add(map);
            map = new HashMap<String, Object>();
        } else {
            map.put("key1", key);
            map.put("val1", val);
        }
        return map;
    }

    /**
     * 分页查询状态非status的Order数据
     *
     * @param status
     * @param filterParams
     * @param pageable
     * @return 返回对象Order集合
     * @throws BusinessException
     */
    @Transactional(readOnly = true, rollbackFor = Exception.class)
    public XaResult<Page<Order>> findListNEStatusByFilter(
            Integer status, Map<String, Object> filterParams, Pageable pageable) throws BusinessException {
        Map<String, SearchFilter> filters = new HashMap<>();
        //处理一下
        if (XaUtil.isEmpty(filterParams.get("search_orderType"))) {
            if (NumberUtils.toInt(filterParams.get("EQ_isService") + "", 0) == 1) {//服务
                filters.put("orderType", new SearchFilter("orderType", Operator.IN,
                        Arrays.asList(
                                JConstant.Order_CommentType.HOURSE,
                                JConstant.Order_CommentType.INSTIBUTION_VISITING,
                                JConstant.Order_CommentType.TOUR,
                                JConstant.Order_CommentType.SERVICE_NURSE_TRANING)));
            } else {//商品
                filters.put("orderType", new SearchFilter("orderType", Operator.IN,
                        Arrays.asList(
                                JConstant.Order_CommentType.GOODS,
                                JConstant.Order_CommentType.GOODS_EXCHANGE,
                                JConstant.Order_CommentType.ARTWORK)));
            }
        }
        filterParams.remove("EQ_isService");
        filters.putAll(SearchFilter.parse(filterParams));
        if (status == null) {// 默认显示非删除的所有数据
            status = XaConstant.Status.delete;
        }
        filters.put("status", new SearchFilter("status", Operator.NE, status));

        Page<Order> page = orderRepository.findAll(DynamicSpecifications
                .bySearchFilter(filters.values(), Order.class), pageable);
        XaResult<Page<Order>> xr = new XaResult<Page<Order>>();
        xr.setObject(page);
        LOGGER.info("后台----->分页查询实体集合（状态不等于）----->Order");
        return xr;
    }

    /**
     * 分页查询状态status的Order数据
     *
     * @param status
     * @param filterParams
     * @param pageable
     * @return 返回对象Order集合
     * @throws BusinessException
     */
    @Transactional(readOnly = true, rollbackFor = Exception.class)
    public XaResult<Page<Order>> findListEQStatusByFilter(
            Integer status, Map<String, Object> filterParams, Pageable pageable) throws BusinessException {
        Map<String, SearchFilter> filters = SearchFilter.parse(filterParams);
        if (status == null) {// 默认显示正常数据
            status = XaConstant.Status.valid;
        }
        filters.put("status", new SearchFilter("status", Operator.EQ, status));
        Page<Order> page = orderRepository.findAll(DynamicSpecifications
                .bySearchFilter(filters.values(), Order.class), pageable);
        XaResult<Page<Order>> xr = new XaResult<Page<Order>>();
        xr.setObject(page);
        LOGGER.info("后台----->分页查询实体集合（状态等于）----->Order");
        return xr;
    }

    /**
     * 保存Order信息
     *
     * @param model
     * @return
     * @throws BusinessException
     */
    @Transactional(rollbackFor = Exception.class)
    public XaResult<Order> saveOrUpdate(Order model) throws BusinessException {
        Order obj = null;
        if (XaUtil.isNotEmpty(model.getId())) {
            obj = orderRepository.findOne(model.getId());
        } else {
            obj = new Order();
        }
        obj.setUserId(XaUtil.isNotEmpty(model.getUserId()) ? model.getUserId() : obj.getUserId());
        obj.setOrderNo(XaUtil.isNotEmpty(model.getOrderNo()) ? model.getOrderNo() : obj.getOrderNo());
        obj.setOrder_PAY_DateTime(XaUtil.isNotEmpty(model.getOrder_PAY_DateTime()) ? model.getOrder_PAY_DateTime() : obj.getOrder_PAY_DateTime());
        obj.setOrder_DeliverGoods_DateTime(XaUtil.isNotEmpty(model.getOrder_DeliverGoods_DateTime()) ? model.getOrder_DeliverGoods_DateTime() : obj.getOrder_DeliverGoods_DateTime());
        obj.setOrder_Sucess_DateTime(XaUtil.isNotEmpty(model.getOrder_Sucess_DateTime()) ? model.getOrder_Sucess_DateTime() : obj.getOrder_Sucess_DateTime());
        obj.setOrderReceivingDatetime(XaUtil.isNotEmpty(model.getOrderReceivingDatetime()) ? model.getOrderReceivingDatetime() : obj.getOrderReceivingDatetime());
        obj.setOrder_Dead_DateTime(XaUtil.isNotEmpty(model.getOrder_Dead_DateTime()) ? model.getOrder_Dead_DateTime() : obj.getOrder_Dead_DateTime());
        obj.setOrderState(XaUtil.isNotEmpty(model.getOrderState()) ? model.getOrderState() : obj.getOrderState());
        obj.setPaymentKind(XaUtil.isNotEmpty(model.getPaymentKind()) ? model.getPaymentKind() : obj.getPaymentKind());
        obj.setOrderTotalPirce(XaUtil.isNotEmpty(model.getOrderTotalPirce()) ? model.getOrderTotalPirce() : obj.getOrderTotalPirce());
        obj.setPostage(XaUtil.isNotEmpty(model.getPostage()) ? model.getPostage() : obj.getPostage());
        obj.setDeducted_money(XaUtil.isNotEmpty(model.getDeducted_money()) ? model.getDeducted_money() : obj.getDeducted_money());
        obj.setExpressCompany(XaUtil.isNotEmpty(model.getExpressCompany()) ? model.getExpressCompany() : obj.getExpressCompany());
        obj.setExpressNumber(XaUtil.isNotEmpty(model.getExpressNumber()) ? model.getExpressNumber() : obj.getExpressNumber());
        obj.setConsigneeAdress(XaUtil.isNotEmpty(model.getConsigneeAdress()) ? model.getConsigneeAdress() : obj.getConsigneeAdress());
        obj.setConsigneeName(XaUtil.isNotEmpty(model.getConsigneeName()) ? model.getConsigneeName() : obj.getConsigneeName());
        obj.setConsigneeTel(XaUtil.isNotEmpty(model.getConsigneeTel()) ? model.getConsigneeTel() : obj.getConsigneeTel());
        obj.setOrderVilidaty(XaUtil.isNotEmpty(model.getOrderVilidaty()) ? model.getOrderVilidaty() : obj.getOrderVilidaty());
        obj.setOrderType(XaUtil.isNotEmpty(model.getOrderType()) ? model.getOrderType() : obj.getOrderType());
        obj.setService_object_id(XaUtil.isNotEmpty(model.getService_object_id()) ? model.getService_object_id() : obj.getService_object_id());
        obj.setService_num(XaUtil.isNotEmpty(model.getService_num()) ? model.getService_num() : obj.getService_num());
        obj.setService_price(XaUtil.isNotEmpty(model.getService_price()) ? model.getService_price() : obj.getService_price());
        obj.setService_userName(XaUtil.isNotEmpty(model.getService_userName()) ? model.getService_userName() : obj.getService_userName());
        obj.setService_phone(XaUtil.isNotEmpty(model.getService_phone()) ? model.getService_phone() : obj.getService_phone());
        obj.setService_idCard(XaUtil.isNotEmpty(model.getService_idCard()) ? model.getService_idCard() : obj.getService_idCard());
        obj.setService_appointment_time(XaUtil.isNotEmpty(model.getService_appointment_time()) ? model.getService_appointment_time() : obj.getService_appointment_time());
        obj.setStandardIds(XaUtil.isNotEmpty(model.getStandardIds()) ? model.getStandardIds() : obj.getStandardIds());
        obj.setGoodsTotalPrices(XaUtil.isNotEmpty(model.getGoodsTotalPrices()) ? model.getGoodsTotalPrices() : obj.getGoodsTotalPrices());
        obj.setLeaveMsg(XaUtil.isNotEmpty(model.getLeaveMsg()) ? model.getLeaveMsg() : obj.getLeaveMsg());
        obj.setBillType(XaUtil.isNotEmpty(model.getBillType()) ? model.getBillType() : obj.getBillType());
        obj.setBillTitle(XaUtil.isNotEmpty(model.getBillTitle()) ? model.getBillTitle() : obj.getBillTitle());
        obj.setBillContent(XaUtil.isNotEmpty(model.getBillContent()) ? model.getBillContent() : obj.getBillContent());
        obj.setOfflinePrices(XaUtil.isNotEmpty(model.getOfflinePrices()) ? model.getOfflinePrices() : obj.getOfflinePrices());
        obj.setQueryId(XaUtil.isNotEmpty(model.getQueryId()) ? model.getQueryId() : obj.getQueryId());
        obj.setRefuOrderNo(XaUtil.isNotEmpty(model.getRefuOrderNo()) ? model.getRefuOrderNo() : obj.getRefuOrderNo());
        obj.setRefundStatus(XaUtil.isNotEmpty(model.getRefundStatus()) ? model.getRefundStatus() : obj.getRefundStatus());

        if (Integer.parseInt(obj.getOrderType()) == JConstant.Order_CommentType.SERVICE_NURSE_TRANING ||
                Integer.parseInt(obj.getOrderType()) == JConstant.Order_CommentType.INSTIBUTION_VISITING) {
            //64:护理培训|培训义工
            //65:机构参观
            //没有评价,直接订单完成
            obj.setOrderState(JConstant.OrderStatus.SUCCES_TRADE + "");
            obj.setOrder_Sucess_DateTime(DateUtils.getToDayStr());
        }

        obj = orderRepository.save(obj);
        XaResult<Order> xr = new XaResult<Order>();
        xr.setObject(obj);
        LOGGER.info("后台新增或编辑数据成功！");
        return xr;
    }

    /**
     * @param modelId
     * @return
     * @Title: 订单发货send
     * @Description: 发货之后修改订单
     */
    @Transactional(rollbackFor = Exception.class)
    public XaResult<Boolean> sendOrders(
            String[] modelId,
            String expressCompany,
            String expressNumber) throws BusinessException {
        XaResult<Boolean> xr = new XaResult<Boolean>();
        for (String id : modelId) {
            String sql = "update tb_xa_order o set o.order_state = ?,o.express_company= ? ,o.express_number= ?, o.order_deliver_goods_date_time  = ? where o.id= ? ";
            List params = Lists.newArrayList(JConstant.OrderStatus.UN_CONSIGNEE, expressCompany, expressNumber, DateUtils.getToDayStr(), Long.parseLong(id));
            this.update(sql, params);
        }
        xr.setObject(true);
        return xr;
    }


    /**
     * 修改Order状态，可一次修改多条   3删除  -1锁定  1正常
     * //@param userId
     *
     * @param modelIds
     * @param status
     * @return 返回Order对象
     * @throws BusinessException
     */
    @Transactional(rollbackFor = Exception.class)
    public XaResult<Order> multiOperate(
            String modelIds, Integer status) throws BusinessException {
        XaResult<Order> xr = new XaResult<Order>();
        if (status == null) {
            status = XaConstant.Status.delete;
        }
        if (modelIds != null) {
            String[] ids = modelIds.split(",");
            for (String id : ids) {
                Order obj = orderRepository.findByIdAndStatusNot(Long.parseLong(id), status);
                if (XaUtil.isNotEmpty(obj)) {
                    obj.setStatus(status);
                    obj = orderRepository.save(obj);
                }
            }
        }
        LOGGER.info("批量修改数据状态成功！");
        return xr;
    }

    @Override
    public void exportdata(Map<String, Object> filterParams,
                           HttpServletResponse response, String modelIds) throws BusinessException {
        Pageable pageable = WebUitl.buildPageRequest(0, Integer.MAX_VALUE, "[{property:'createTime',direction:'DESC'}]");
        Page<Order> page = this.findListNEStatusByFilter(XaConstant.Status.delete, filterParams, pageable).getObject();
        List<Order> orderVoList = new ArrayList<>();
        if (XaUtil.isNotEmpty(page) && XaUtil.isNotEmpty(page.getContent())) {
            orderVoList.addAll(page.getContent());
        }

        //excel结构
        List<ExcelColumn> excelColumns = new ArrayList<ExcelColumn>();
        excelColumns.add(new ExcelColumn(0, "orderNo", "主订单编号", Cell.CELL_TYPE_STRING));
        excelColumns.add(new ExcelColumn(1, "orderTotalPirce", "订单总价", Cell.CELL_TYPE_STRING));
        excelColumns.add(new ExcelColumn(2, "orderType", "订单类型", Cell.CELL_TYPE_STRING));
        excelColumns.add(new ExcelColumn(3, "consigneeName", "联系人", Cell.CELL_TYPE_STRING));
        excelColumns.add(new ExcelColumn(4, "consigneeTel", "手机号", Cell.CELL_TYPE_STRING));
        excelColumns.add(new ExcelColumn(5, "orderState", "订单状态", Cell.CELL_TYPE_STRING));
        excelColumns.add(new ExcelColumn(6, "createTime", "下单时间", Cell.CELL_TYPE_STRING));
        excelColumns.add(new ExcelColumn(7, "paymentKind", "支付方式", Cell.CELL_TYPE_STRING));

        // 需要特殊转换的单元 map的可以必须好实体的类型一致
        /**
         * {@link JConstant.Order_CommentType}
         */
        Map<String, Map> excelColumnsConvertMap = new HashMap<>();
        Map<String, String> isReceive = new HashMap<>();
        isReceive.put("1", "普通商品");
        isReceive.put("2", "兑换商品");
        isReceive.put("3", "玩 /达人/作品/艺术品");
        isReceive.put("51", "住");
        isReceive.put("52", "机构参观");
        isReceive.put("53", "玩旅游/游学");
        isReceive.put("64", "旅护理培训|培训义工");
        excelColumnsConvertMap.put("orderType", isReceive);

        /**
         * {@link JConstant.OrderStatus}
         */
        Map<String, String> isReceive1 = new HashMap<>();
        isReceive1.put("0", "未支付");
        isReceive1.put("1", "已支付");
        isReceive1.put("2", "待收货");
        isReceive1.put("3", "已经消费/已经收货");
        isReceive1.put("4", "交易完成");
        isReceive1.put("5", "交易关闭");
        excelColumnsConvertMap.put("orderState", isReceive1);

        /**
         * {@link JConstant.PayType}
         */
        Map<Integer, String> isReceive2 = new HashMap<>();
        try {
            Map<Integer, String> map = ReflectionUtils.covetConstaintClassToMap(JConstant.PayType.class);
            isReceive2.putAll(map);
            excelColumnsConvertMap.put("paymentKind", isReceive2);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(e.getLocalizedMessage());
        }

        //设置头部
        ExcelHead head = new ExcelHead();
        head.setRowCount(1); // 模板中头部所占行数
        head.setColumns(excelColumns);  // 列的定义
        head.setColumnsConvertMap(excelColumnsConvertMap); // 列的转换
        //执行导出,第一个null是response参数，用来输出到浏览器，第二个null是要导出的数据集合
        ExcelHelper.getInstanse().exportExcelFile(response, head, orderVoList);
    }

    /**
     * 更新库存
     *
     * @return
     * @throws BusinessException
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updatetockNum() throws BusinessException {
        //查询所有的未支付的订单
        //订单未支付-->订单取消
        //库存归还
    }

}
